/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.business.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.business.domain.Hljg;
import me.zhengjie.business.domain.Qy;
import me.zhengjie.business.domain.Zhsq;
import me.zhengjie.business.domain.sup.Rygl;
import me.zhengjie.business.domain.vo.*;
import me.zhengjie.business.repository.*;
import me.zhengjie.config.DebugProperties;
import me.zhengjie.domain.LocalStorage;
import me.zhengjie.repository.LocalStorageRepository;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.business.service.QyService;
import me.zhengjie.business.service.dto.QyDto;
import me.zhengjie.business.service.dto.QyQueryCriteria;
import me.zhengjie.business.service.mapstruct.QyMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author xiahongbo
* @date 2022-07-14
**/
@Slf4j
@Service
@RequiredArgsConstructor
public class QyServiceImpl implements QyService {

    private final RyglRepository ryglRepository;
    private final QyRepository qyRepository;
    private final QyMapper qyMapper;
    private final ZhsqRepository zhsqRepository;
    private final HljgRepository hljgRepository;
    private final FpryRepository fpryRepository;
    private final LocalStorageRepository localStorageRepository;

    @Override
    public Map<String,Object> queryAll(QyQueryCriteria criteria, Pageable pageable){
        Page<Qy> page = qyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(qyMapper::toDto));
    }

    @Override
    public Map<String, Object> queryList(String hilgId, String zt, String blurry, String area, Pageable pageable) {
        Page<ZhgkQyVo> page =  qyRepository.queryList(blurry, area, hilgId, zt, pageable);
        return PageUtil.toPage(page);
        /*
        List<Object> list = qyRepository.queryList(hljgId, zt, blurry, pageable);
        List<DqyVo> vos = new ArrayList<>();
        for (Object obj : list) {
            log.info("queryList Object : {} ", obj);
            Object[] arr = (Object[]) obj;

            DqyVo vo = new DqyVo();
            vo.setBisZhsqId(Long.parseLong(arr[0].toString()));
            vo.setBisZhsqSnryXm((String)arr[1]);
            vo.setBisZhsqSnryXb((String)arr[2]);
            vo.setBisZhsqSnrySfz((String)arr[3]);
            vo.setBisZhsqSndj((String)arr[4]);
            vo.setBisZhsqLxdh((String)arr[5]);
            vo.setBisZhsqJhrxm((String)arr[6]);
            vo.setBisZhsqJhrdh((String)arr[7]);
            vo.setBisZhsqHldz((String)arr[8]);
            vo.setBisZhsqNl((String)arr[9]);
            vo.setBisZhsqAdl((String)arr[10]);
            vo.setBisZhsqGx((String)arr[11]);
            vo.setBisQyZt((String)arr[12]);
            vo.setSqsj((String)arr[13]);
            vo.setBisZhsqHldzXxdz((String)arr[14]);

            vos.add(vo);
        }
        log.info("-------------- {} ", vos);
        return PageUtil.toPage(vos, vos.size());
        */
    }

    @Override
    public Map<String, Object> queryAllQyList(String hljgId, String zt, String blurry, Pageable pageable) {
        List<Object> list = qyRepository.queryAllQyList(hljgId, zt, blurry, pageable);
        List<DqyVo> vos = new ArrayList<>();
        for (Object obj : list) {
            log.info("queryList Object : {} ", obj);
            Object[] arr = (Object[]) obj;

            DqyVo vo = new DqyVo();
            vo.setBisZhsqId(Long.parseLong(arr[0].toString()));
            vo.setBisZhsqSnryXm((String)arr[1]);
            vo.setBisZhsqSnryXb((String)arr[2]);
            vo.setBisZhsqSnrySfz((String)arr[3]);
            vo.setBisZhsqSndj((String)arr[4]);
            vo.setBisZhsqLxdh((String)arr[5]);
            vo.setBisZhsqJhrxm((String)arr[6]);
            vo.setBisZhsqJhrdh((String)arr[7]);
            vo.setBisZhsqHldz((String)arr[8]);
            vo.setBisZhsqNl((String)arr[9]);
            vo.setBisZhsqAdl((String)arr[10]);
            vo.setBisZhsqGx((String)arr[11]);
            vo.setBisQyZt((String)arr[12]);
            vo.setSqsj((String)arr[13]);
            vo.setBisGsglIszf((String)arr[14]);
            vo.setBisQyId((String)arr[15]);

            vos.add(vo);
        }
        log.info("-------------- {} ", vos);
        return PageUtil.toPage(vos, vos.size());
    }

    @Override
    public Page<Qy> queryIncompleteList(String blurry, Pageable pageable) {
        String zt = "qygl02";

        Page<Qy> page = qyRepository.queryAllByPgUserId(zt, SecurityUtils.getCurrentUserId(), blurry, pageable);
//        List<DqyVo> vos = new ArrayList<>();
//        for (Object obj : list.getContent()) {
//            log.info("queryList Object : {} ", obj);
//            Object[] arr = (Object[]) obj;
//
//            DqyVo vo = new DqyVo();
//            vo.setBisZhsqId(Long.parseLong(arr[0].toString()));
//            vo.setBisZhsqSnryXm((String)arr[1]);
//            vo.setBisZhsqSnryXb((String)arr[2]);
//            vo.setBisZhsqSnrySfz((String)arr[3]);
//            vo.setBisZhsqSndj((String)arr[4]);
//            vo.setBisZhsqLxdh((String)arr[5]);
//            vo.setBisZhsqJhrxm((String)arr[6]);
//            vo.setBisZhsqJhrdh((String)arr[7]);
//            vo.setBisZhsqHldz((String)arr[8]);
//            vo.setBisZhsqNl((String)arr[9]);
//            vo.setBisZhsqAdl((String)arr[10]);
//            vo.setBisZhsqGx((String)arr[11]);
//            vo.setBisQyZt((String)arr[12]);
//            vo.setSqsj((String)arr[13]);
//            vo.setBisQyId((String)arr[14]);
//            vos.add(vo);
//            obj = vo;
//        }
//        log.info("-------------- {} ", vos);
        return page;
    }
    @Override
    public Page<Qy> queryMpList(QyQueryCriteria criteria, Pageable pageable) {
        Rygl rygl = ryglRepository.findByBisRyglUserId(SecurityUtils.getCurrentUserId());
        String hljgId = rygl.getGsgl().getBisGsglId();

        criteria.setBisQyZt("qygl03");
        criteria.setBisQyHljgId(hljgId);

        Page<Qy> page = qyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
//        Page<Qy> page = qyRepository.queryByBisQyHljgIdAndBisQyZtAndZhsq(hljgId, zt, bisZhsqSnryXm, pageable);
//        List<DqyVo> vos = new ArrayList<>();
//        for (Object obj : list.getContent()) {
//            log.info("queryList Object : {} ", obj);
//            Object[] arr = (Object[]) obj;
//
//            DqyVo vo = new DqyVo();
//            vo.setBisZhsqId(Long.parseLong(arr[0].toString()));
//            vo.setBisZhsqSnryXm((String)arr[1]);
//            vo.setBisZhsqSnryXb((String)arr[2]);
//            vo.setBisZhsqSnrySfz((String)arr[3]);
//            vo.setBisZhsqSndj((String)arr[4]);
//            vo.setBisZhsqLxdh((String)arr[5]);
//            vo.setBisZhsqJhrxm((String)arr[6]);
//            vo.setBisZhsqJhrdh((String)arr[7]);
//            vo.setBisZhsqHldz((String)arr[8]);
//            vo.setBisZhsqNl((String)arr[9]);
//            vo.setBisZhsqAdl((String)arr[10]);
//            vo.setBisZhsqGx((String)arr[11]);
//            vo.setBisQyZt((String)arr[12]);
//            vo.setSqsj((String)arr[13]);
//
//            vos.add(vo);
//            obj = vo;
//        }
//        log.info("-------------- {} ", vos);
        return page;
    }

    @Override
    public List<QyDto> queryAll(QyQueryCriteria criteria){
        List<Qy> all = qyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        return qyMapper.toDto(qyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public QyDto findById(String bisQyId) {
        Qy qy = qyRepository.findById(bisQyId).orElseGet(Qy::new);
        ValidationUtil.isNull(qy.getBisQyId(),"Qy","bisQyId",bisQyId);
        return qyMapper.toDto(qy);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QyDto create(Qy resources) {
        qyRepository.updateBisGsglIszfByBisQyZhsqId("0",resources.getBisQyZhsqId());
        Zhsq zhsq = zhsqRepository.findById(resources.getBisQyZhsqId()).get();
        zhsq.setBisZhsqZt("12");
        zhsqRepository.save(zhsq);
        resources.setBisQyId(IdUtil.simpleUUID());
        resources.setBisQyZt("qygl01");
        resources.setBisQyMpzt("qygl01");
        resources.setBisGsglIszf("1");
        return qyMapper.toDto(qyRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sign(Qy resources) {

        Qy qy = qyRepository.findById(resources.getBisQyId()).orElseGet(Qy::new);
//        ValidationUtil.isNull( qy.getBisQyId(),"Qy","id",resources.getBisQyId());
        qy.setBisQyZt("qygl03");
        qyRepository.save(qy);
        qy.setBisQyQysj(resources.getBisQyQysj());
//        qy.setBisQyQysj(new Date());
        qyRepository.save(qy);
        Optional<Zhsq> zhsqOptional = zhsqRepository.findById(qy.getBisQyZhsqId());
        Zhsq zhsq = zhsqOptional.get();
        Optional<Hljg> hljgOptional = hljgRepository.findById(qy.getBisQyHljgId());
        zhsq.setHljg(hljgOptional.get());
        zhsq.setBisZhsqHljgBm(hljgOptional.get().getBisGsglYljgdm());

        //log.info("居家失能老人：重度失能");
        //zhsq.setBisZhsqSndj("重度失能");
        //Date dykkrq = qy.getBisQyQysj();
        //Date tempDate = DateTimeUtil.addMonths(dykkrq, 6);
        //Date dyjsrq = DateTimeUtil.addDays(tempDate, -1);
        //log.info("待遇开始日期 : {}，待遇结束日期 : {}", dykkrq,dyjsrq);
        //zhsq.setBisZhsqDykkrq(dykkrq);
        //zhsq.setBisZhsqDyjsrq(dyjsrq);
        zhsq.setBisZhsqZt("13");
        zhsqRepository.save(zhsq);

        // 更新分配人员表的完成状态
        fpryRepository.updateFpryWczt(zhsq.getBisZhsqId(), DefaultUtil.RYLX_QYRY);
        if(!DebugProperties.debug) {

        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Qy resources) {
        Qy qy = qyRepository.findById(resources.getBisQyId()).orElseGet(Qy::new);
        ValidationUtil.isNull( qy.getBisQyId(),"Qy","id",resources.getBisQyId());
        qy.copy(resources);
        qyRepository.save(qy);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateQyzfzt(String qyid) {
        Qy qy = qyRepository.findById(qyid).orElseGet(Qy::new);
        qy.setBisGsglIszf("0");
        qyRepository.save(qy);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String bisQyId : ids) {
            qyRepository.deleteById(bisQyId);
        }
    }

    @Override
    public void download(List<QyDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (QyDto qy : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public JSONObject checkChooseHljg(Long zhid, String fwlx) {
        Qy qy = qyRepository.queryByBisQyZhsqIdAndBisGsglIszf(zhid, "1");
        JSONObject jsonObject = new JSONObject();
        if(qy == null) {
            jsonObject.put("flag", "1");
            jsonObject.put("msg", "尚未关联护理机构，可以选择");
        } else {
            String qyzt = qy.getBisQyZt();
            if(!qyzt.equals("qygl01")){
                jsonObject.put("flag", "0");
                jsonObject.put("msg", "已分配签约人员，不允许修改");
            }else{

                Qy fistQy = qyRepository.queryFirstByZhid(zhid);
                Date lrsj = fistQy.getLrsj();
                Date currentDate = DateTime.now();

                long starttime = DateTimeUtil.Date2MS(lrsj);
                long endtime = DateTimeUtil.Date2MS(currentDate);
                long rs = (endtime-starttime)/(1000 * 3600 * 24);

                if(rs <= 24) {
                    List<Qy> isExstQyList = qyRepository.queryByBisQyZhsqId(zhid);
                    if(isExstQyList.size() >= 2) {
                        jsonObject.put("flag", "0");
                        jsonObject.put("msg", "24小时以内，只可以重新选择一次");
                    } else {
                        jsonObject.put("flag", "1");
                        jsonObject.put("msg", "只选择过一次，可以重新选择");
                    }
                } else {
                    jsonObject.put("flag", "0");
                    jsonObject.put("msg", "超过24小时，无法重新选择护理机构");
                }
            }
        }

        return jsonObject;
    }

    @Override
    public Map<String, Object> qyHomeJY(QyQueryCriteria qyHomeJyVO,Pageable pageable) {
        Page<QyHomeJyVO> page =  qyRepository.queryQyHomeJYList(qyHomeJyVO.getXm(),qyHomeJyVO.getQyzt(),qyHomeJyVO.getHljg(),pageable);
        return PageUtil.toPage(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void qyHomeJYUpdate(HashMap<String, String> map) throws ParseException {
        String qyid = map.get("qyid");
        long zhid = Long.parseLong(map.get("zhid"));
        String jysj = map.get("jysj");
        String fileIds = map.get("fileIds");

        jysj = jysj.replace("Z", " UTC");
        SimpleDateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
        Date date = utcFormat.parse(jysj);

        // 1.修改签约状态（已解约）
        Qy byId = qyRepository.findById(qyid).orElseGet(Qy::new);
        byId.setBisQyZt("qygl04");
        qyRepository.save(byId);

        // 2.修改照护状态（待遇终止），修改解约时间（待遇结束日期）
        //Zhsq zhsq = zhsqRepository.findById(zhid).orElseGet(Zhsq::new);
        //zhsq.setBisZhsqZt("90");
        //zhsq.setBisZhsqDyjsrq(date);
        //zhsqRepository.save(zhsq);

        // 3.上传图片 关联签约id
        if(fileIds != null && !fileIds.equals("")){
            log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 - 关联附件 ");
            String[] picIds = fileIds.split(",");
            for (String picId:picIds) {
                Long storage_id = Long.parseLong(picId);
                LocalStorage localStorage = localStorageRepository.findById(storage_id).orElseGet(LocalStorage::new);
                localStorage.setYwid(qyid);
                localStorageRepository.save(localStorage);
            }
        }

    }

    @Override
    public Map<String, Object> qyHomeYjy(QyQueryCriteria qyHomeJyVO, Pageable pageable) {
        Page<QyHomeJyVO> page =  qyRepository.queryQyHomeJYList(qyHomeJyVO.getXm(),qyHomeJyVO.getQyzt(), qyHomeJyVO.getHljg(), pageable);
        return PageUtil.toPage(page);
    }

    @Override
    public void qyHomeCxjgUpdate(HashMap<String, String> qyHomeJyVO) {
        String qyid = qyHomeJyVO.get("qyid");
        String bisGsglId = qyHomeJyVO.get("bisGsglId");
        Optional<Qy> byId = qyRepository.findById(qyid);
        Qy sourceQy = byId.get();
        Qy updateQy = new Qy();
        BeanUtils.copyProperties(sourceQy,updateQy);
        // 新建 （更新居家）
        updateQy.setBisQyId(null);
        updateQy.setBisQyHljgId(bisGsglId);
        qyRepository.save(updateQy);
        // 更新 （原来作废）
        sourceQy.setBisGsglIszf("0");
        qyRepository.save(sourceQy);
    }

    @Override
    public String findByZhId(Long bisZhsqId) {
        String gsName = qyRepository.findByZhId(bisZhsqId);
        return gsName;
    }
}